import {
  Component,
  EventEmitter,
  Output,
  Input,
  OnChanges,
  ChangeDetectorRef
} from "@angular/core";
import {
  NavController,
  AlertController,
  ActionSheetController
} from "ionic-angular";
import { Storage } from "@ionic/storage";
import { HttpService } from "../../../../providers/http.service";
import { DebrisHalfMonBean } from "../bean/debrisHalfMon.bean";
import { Camera, CameraOptions } from "@ionic-native/camera";
import { CommonFunc } from "../../../../providers/commonFunc";
import { appConfig } from "../../../../providers/config";
import {
  FileTransfer,
  FileUploadOptions,
  FileTransferObject
} from "@ionic-native/file-transfer";
import { File } from "@ionic-native/file";
import { PhotoViewer } from "@ionic-native/photo-viewer";

@Component({
  selector: "debris-half",
  templateUrl: "debris-half-mon.html",
  providers: [HttpService, CommonFunc]
})
export class DebrisHalf implements OnChanges {
  private showOK: boolean = false;
  private showError: boolean = false;
  private debrisHalfMonBean: DebrisHalfMonBean = new DebrisHalfMonBean();
  @Output() next: EventEmitter<any> = new EventEmitter();
  @Input() inValue: any;
  private appConfig: any;
  private ElevaType: string;
  constructor(
    public navCtrl: NavController,
    private storage: Storage,
    private httpService: HttpService,
    private alert: AlertController,
    private camera: Camera,
    private commonFunc: CommonFunc,
    private transfer: FileTransfer,
    private file: File,
    private photoViewer: PhotoViewer,
    private ActionSheet: ActionSheetController,
    public cd: ChangeDetectorRef
  ) {
    // console.log(this.debrisHalfMonBean.cproomEnvironment.isOk);
    this.appConfig = appConfig;
  }
  ngOnChanges() {
    if (this.inValue.data["isLook"]) {
      this.storage.get(this.inValue.data["elevatorNum"] + '-his-' + "debris-half").then(data => {
        if (data) {
          this.debrisHalfMonBean = data;
          this.debrisHalfMonBean.type = this.inValue.data["type"];
          this.debrisHalfMonBean.elevatorNum = this.inValue.data["elevatorNum"];
          this.cd.detectChanges();
        }
      });
    } else {
      this.storage.get(this.inValue.data["elevatorNum"] + "debris-half").then(data => {
        if (data) {
          this.debrisHalfMonBean = data;
          this.debrisHalfMonBean.type = this.inValue.data["type"];
          this.debrisHalfMonBean.elevatorNum = this.inValue.data["elevatorNum"];
          this.cd.detectChanges();
        }
      });
    }


    this.debrisHalfMonBean.elevatorNum = this.inValue.data["elevatorNum"];
    this.debrisHalfMonBean.type = this.inValue.data["type"];
    this.ElevaType = this.inValue.data["ElevaType"];
  }

  /**
   * 处理检查项无此项的问题
   * @param name
   */
  doIsNull(name){
    if(name == 'pitStop' || name == 'stopDevice' || name == 'manualEmergencyOperation'){ //必输项，不能为空
      return;
    }
    this.debrisHalfMonBean[name].isOk = null;
    this.cd.detectChanges();
  }
  doOk(name) {
    this.debrisHalfMonBean[name].isOk = !this.debrisHalfMonBean[name].isOk;
    this.cd.detectChanges();
  }
  doError(name) {
    this.debrisHalfMonBean[name].isOk = !this.debrisHalfMonBean[name].isOk;
    // this.showOK = false;
    // this.showError = !this.showError;
  }
  doCamera(name, i) {
    let options: CameraOptions = {
      quality: 85, // destinationType: this.camera.DestinationType.DATA_URL,
      // encodingType: this.camera.EncodingType.JPEG,
      mediaType: this.camera.MediaType.PICTURE,
      targetWidth: 1500,
      targetHeight: 1500,
      correctOrientation: true
    };
    this.camera.getPicture(options).then(
      imageData => {
        if (!this.commonFunc.hasNetWork()) {
          if (i == "c") {
            this.debrisHalfMonBean[name].picUrl.push(imageData);
          } else {
            this.debrisHalfMonBean[name].picUrl[i] = imageData;
          }
          return;
        }
        const options: FileUploadOptions = {};
        let serverUrl = encodeURI(
          appConfig.IP_URL + appConfig.API.upload
        );
        //let serverUrl =  encodeURI('http://192.168.43.242:8080/upload/base.ctrl');
        options.fileKey = "file";
        options.fileName = "test.jpg";
        options.mimeType = "image/jpeg";
        const fileTransfer: FileTransferObject = this.transfer.create();
        fileTransfer.upload(imageData, serverUrl, options).then(restul => {
          let aa = JSON.parse(restul["response"]);
          if (aa["status"] == 200) {
            if (aa["data"].length > 0) {
              if (i == "c") {
                this.debrisHalfMonBean[name].picUrl.push(aa["data"]);
              } else {
                this.debrisHalfMonBean[name].picUrl[i] = aa["data"];
              }
            }
          }
          this.cd.detectChanges();
        });
      },
      err => {
        // Handle error
      }
    );
  }

    doSubmit() {
        // let list = ['manualEmergencyOperation','pitStop'];
        // let res = this.commonFunc.vlidate(this.debrisHalfMonBean,list)

        // if(res){
        // let param = this.commonFunc.convertBeanToString(this.debrisHalfMonBean);
        if (!this.inValue.data["isLook"]) {
            this.storage.set(this.inValue.data["elevatorNum"] + "debirs-half", this.debrisHalfMonBean).then(() => {
                this.next.emit({next: true, ElevaType: this.ElevaType});
            });
        } else {
            this.next.emit({next: true, ElevaType: this.ElevaType});
        }

        // }else{
        //   let toas =  this.commonFunc.showInsideErrorToast({errorMessage:'请拍完所有照片'});
        //   toas.present();
        //   return;
        // }
    }
  doLast() {
    this.next.emit({ next: false });
  }

  onHold(name, param) {
    let actionSheet = this.ActionSheet.create({
      buttons: [
        {
          text: "重拍",
          role: "重拍",
          handler: () => {
            let i = this.debrisHalfMonBean[name].picUrl.indexOf(param);
            this.doCamera(name, i);
          }
        },
        {
          text: "查看大图",
          role: "查看大图",
          handler: () => {
            let url: string = param;

            this.photoViewer.show(this.whaturl(url), null, { share: false });
          }
        },
        {
          text: "删除",
          handler: () => {
            let i = this.debrisHalfMonBean[name].picUrl.indexOf(param);
            this.debrisHalfMonBean[name].picUrl.splice(i, 1);
          }
        },
        {
          text: "取消",
          role: "取消",
          handler: () => {
            //console.log('Cancel clicked');
          }
        }
      ]
    });
    actionSheet.present();
  }

  whaturl(url) {
    if ((url + "").indexOf("file") < 0) {
      return this.appConfig.IP_URL + this.appConfig.API.getUpload + url;
    } else {
      return url;
    }
  }
}
